<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：后台公用控制器。
 *
 **/

namespace Qwadmin\Controller;

use Common\Controller\BaseController;
use Think\Auth;

class ComController extends BaseController
{
    public $USER;

    public function _initialize()
    {

        C(setting());
        if (!C("COOKIE_SALT")) {
            $this->error('请配置COOKIE_SALT信息');
        }
 /**
         * 不需要登录控制器
         */
        if (in_array(CONTROLLER_NAME, array("Login"))) {
            return true;
        }
		elseif (in_array(CONTROLLER_NAME,array("User"))) {
            if (in_array(ACTION_NAME,array("testsend","processd","threadupdatepush","thread_send_info","sendimgs","subscribe_to"))) {
                 return true;
            }
        }
		
        //检测是否登录
        $flag =  $this->check_login();
        $url = U("login/index");
        if (!$flag) {
            header("Location: {$url}");
            exit(0);
        }
        $m = M();
        $prefix = C('DB_PREFIX');
        $UID = $this->USER['uid'];
        $userinfo = $m->query("SELECT * FROM {$prefix}auth_group g left join {$prefix}auth_group_access a on g.id=a.group_id where a.uid=$UID");
        $Auth = new Auth();
        $allow_controller_name = array('Upload');//放行控制器名称
        $allow_action_name = array();//放行函数名称
        if ($userinfo[0]['group_id'] != 1 && !$Auth->check(CONTROLLER_NAME . '/' . ACTION_NAME,
                $UID) && !in_array(CONTROLLER_NAME, $allow_controller_name) && !in_array(ACTION_NAME,
                $allow_action_name)
        ) {
            $this->error('没有权限访问本页面!');
        }

        $user = member(intval($UID));
        $this->assign('user', $user);


        $current_action_name = ACTION_NAME == 'edit' ? "index" : ACTION_NAME;
        $current = $m->query("SELECT s.id,s.title,s.name,s.tips,s.pid,p.pid as ppid,p.title as ptitle FROM {$prefix}auth_rule s left join {$prefix}auth_rule p on p.id=s.pid where s.name='" . CONTROLLER_NAME . '/' . $current_action_name . "'");
        $this->assign('current', $current[0]);


        $menu_access_id = $userinfo[0]['rules'];

        if ($userinfo[0]['group_id'] != 1) {

            $menu_where = "AND id in ($menu_access_id)";

        } else {

            $menu_where = '';
        }
        $menu = M('auth_rule')->field('id,title,pid,name,icon')->where("islink=1 $menu_where ")->order('o ASC')->select();
        $menu = $this->getMenu($menu);
        $this->assign('menu', $menu);

    }


    protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();
        //修复父类设置islink=0，但是子类仍然显示的bug @感谢linshaoneng提供代码
        foreach( $items as $item ){
            if( $item['pid']==0 ){
                $father_ids[] = $item['id'];
            }
        }
        //----
        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            //修复父类设置islink=0，但是子类仍然显示的bug by shaoneng @感谢linshaoneng提供代码
            if( $item['pid']<>0 && !in_array( $item['pid'], $father_ids )){
                continue;
            }
            //----
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }

    public function check_login(){
        session_start();
        $flag = false;
        $salt = C("COOKIE_SALT");
        $ip = get_client_ip();
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $auth = cookie('auth');
        $uid = session('uid');
        if ($uid) {
            $user = M('member')->where(array('uid' => $uid))->find();

            if ($user) {
                if ($auth ==  password($uid.$user['user'].$ip.$ua.$salt)) {
                    $flag = true;
                    $this->USER = $user;
                }
            }
        }
        return $flag;
    }
	
/**
     * 推送最全小说模板信息
     * */
    protected function sendtemplatezuiquaninfo($domain, $title, $remark, $novel_info, $update_date, $novel_url, $open_id){
        $map["domain"] = $domain;
		$map['is_put'] = 1;
        $platform = D("platform")->where($map)->find();
		$update_templat_id = $platform['update_template_id'];
		//dump($platform);die;
        if(intval($platform["out_time"]) > time())	{
            $token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
        }
        else{
            $token = getWeChatToken($platform["appid"],$platform["secret"]);
        }
        //dump($token);die;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
        $data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"'.$update_templat_id.'",
		           "url":"'.$novel_url.'",       
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"'.$novel_info.'",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$update_date.'",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"'.$remark.'",
	                       "color":"#173177"
	                   }
		           }
				}';
        return $result = weChatCurl($url, 1, $data);
    }
	
	
	/**
     * 推送新生活影音小说模板信息
     * */
    protected function sendtemplatexinshenghuoinfo2($domain, $title, $remark, $novel_info, $update_date, $novel_url, $open_id){
        $map["domain"] = $domain;
        $platform = D("platform")->where($map)->find();
        dump($platform['domain']);
        if(intval($platform["out_time"]) > time())	{
            $token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
        }
        else{
            $token = getWeChatToken($platform["appid"],$platform["secret"]);
        }
        //$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
        //$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk";

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
        $data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"AqrQvI6MkwkeWhlQNZ-oTS4ji1XmeJ_-_i84R2zL70E",
		           "url":"'.$novel_url.'",       
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"'.$novel_info.'",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$update_date.'",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"'.$remark.'",
	                       "color":"#173177"
	                   }
		           }
				}';
        //return $result = weChatCurl($url, 1, $data);
    }

    /**
     * 更新推送模板消息
     */
	
	public function novelpush($novel_id = 0,$chapter_id = 0,$novel_name = '',$order_set = 0,$title = '',$add_time = ''){
    //查询历史记录
    $where = "b.domain = 'www.qichezuoyi.com.cn' or b.domain = 'qikaism.cn'";
        $arr = D('read_history as a')->field('a.open_id,a.novel_id,a.addtime')->join("qw_user as b on b.open_id = a.open_id")
            ->where($where)->order('a.addtime desc')->select();
    foreach ($arr as $re){
            $his_open = $re['open_id'];
            $domain_arr = D('user')->where("open_id='$his_open' and subscribe=1")->find();
            $domain = $domain_arr['domain'];
            //dump($domain);die;
            $his_novel_id = $re['novel_id'];
            //如果说小说id相等就推送信息
            if($novel_id == $his_novel_id) {
                $this->sendtemplatezuiquaninfo($domain, '《' . $novel_name . '》更新到第' . $order_set . '章 ' . $title, '请您点击详情', $novel_name, $add_time, 'http://' . $domain . '/Home/Novel/show/id/' . $chapter_id . '/novel_id/' . $novel_id, $his_open);
            }
        }
    }


	/**
     * 递归获取订阅号open_id
     */
    public function getopenid($url,$next_openid = ''){
        //声明一个静态变量
        static $openid_arr = [];
        //拼接url地址
        $request_url = $url.$next_openid;
        //给微信发送请求
        $result = weChatCurl($request_url);
        //获取openid
        $arr_openida = $result['data']['openid'];
        //将openid装入静态变量中
        $openid_arr[] = $arr_openida;
        //获取next_openid
        $next_openid1 = $result['next_openid'];
        //获取每一次取得的条数
        $count = $result['count'];
        if($count == 10000){
            //如果等于10000就递归
            $this->getopenid($url,$next_openid1);
        }
        //用一个数组来装静态变量
        $arr[] = $openid_arr;
        //将数组返回回去
        return $arr;

    }	
}